import { Helper } from "../helper"
import { TotpItem } from "../../biz/totp-info"
import { parseTotpUri,TotpInfo } from "../../bcat/totp"
import {TotpStorage}  from "../../biz/storage/totp-storage"


Page<{
  inputVisible:boolean,
  dialogChoices:any,
  dialogInput:string,
  helper:Helper
}
,{
  startScaner():void,
  startInputDialog():void,
  onInputDialogConfirmed():void,
  onInputDialogCanceled():void,
  dialogClose():void,
  onTextInput(e: any):void,
  checkTotpResponse(info:TotpInfo):boolean,
  startLoading():void,
  closeLoading():void,
  handleScanResult(scanResult:string):boolean,
  verifyScanResult(scanResult:string):boolean,
  showSuccess(content):void,
  showFail(content):void,
  redirectToList():void
}>({
  data: {
    inputVisible: false,
    dialogChoices: {
      buttons: [{ text: '取消', type: 'default' }, { text: '确定', type: 'primary' }],
      layout: 'horizontal'
    },
    dialogInput:'',
    helper:new Helper()
  },
  onLoad() {
  },
  onReady() {
  },
  onShow() {
  },
  onUnload() {
  },
  startScaner(){
    this.startLoading();
    my.scan({
      success: (res) => {
	      this.closeLoading();
        var scanedResult = JSON.stringify(res);
        //console.log('scaned:'+scanedResult);
        if (this.handleScanResult(res.code)){
            //console.log('handleScanResult success');
            this.showSuccess(`扫描成功`);
            this.redirectToList();
        } else {
          console.error('handleScanResult failed');
        }
      },
      fail: (error) => {
        if (error.error == 10){
          console.info('scan has been cancelled by user');
        } else {
          this.showFail('扫描失败');
          console.error('扫描失败，结果：' + JSON.stringify(error));
        }
	    this.closeLoading();
      }
    });
  },
  startInputDialog() {
    this.setData({ ["inputVisible"]: true });
  },
  onInputDialogConfirmed() {
    var inputResult = this.data.dialogInput;
    this.startLoading();
    if (this.handleScanResult(inputResult)){
        this.closeLoading();
        //console.log('handleScanResult success');
        this.showSuccess('处理成功！');
        this.redirectToList();
    } else {
      console.error('handleScanResult failed');
    }
    this.dialogClose();
  },
  onInputDialogCanceled() {
    //console.log(`user cancelled for input dialog`);
    this.dialogClose();
  },
  dialogClose() {
    this.setData({
      inputVisible: false
    });
  },
  showFail(content):void{
    my.showToast({ type:'fail', content, duration: 2000 });
  },
  showSuccess(content):void{
    my.showToast({ type:'success', content, duration: 2000 });
  },
  onTextInput(e){
    this.setData({
      dialogInput: e.detail.value
    });
  },
  checkTotpResponse(info:TotpInfo):boolean{
    if (info == undefined){
      this.showFail('扫描结果解析失败');
      return false;
    }
	
    //TODO:验证用户
    return true;
  },
  startLoading():void{
    my.showLoading({
          content:"处理中.....",
          delay:0
    });
  },
  verifyScanResult(scanResult:string):boolean{
    if (undefined == scanResult){
      this.showFail('没有扫描到任何信息');
      console.error(`verifyScanResult failed with scanResult is undefined`);
      return false;
    }
    return true;
  },
  closeLoading():void{
    my.hideLoading();
  },
  handleScanResult(scanResult:string):boolean{
    if (false === this.verifyScanResult(scanResult)) return false;
    var info = undefined;
    try{
      info = parseTotpUri(scanResult);
    } catch (error) {
      this.showFail('解析错误，请确认扫描了正确的二维码');
      console.error("handleScanResult failed with ex:"+error.message);
      return false;
    }
    if (false === this.checkTotpResponse(info)) return false;

    //console.log("handleScanResult success:"+JSON.stringify(info));

    var newItem = TotpItem.from(info.issuer,info.accountName,info.secret);
    let totpInfos = this.data.helper.getTotpInfo();
    if (totpInfos.has(newItem.key())){
        //console.log("item is existed in TotpStorage:issuser="+info.issuer+"&accountName="+info.accountName);
        this.showFail('扫描的项目已存在!');
        return false;
    }
    totpInfos.setItem(newItem);
    const r = TotpStorage.fromDefault().save(totpInfos);
    if(r == true ) {
      console.debug("add newItem => save to cache ok!", r);
    }
    else{
      console.debug("add newItem => save to cache failed!", r);
    }
    return true;
  },
  redirectToList():void{
    my.switchTab({
      url: '/pages/index/index'
    });
  }
});



